package com.minzheng.blog.strategy.impl;

import com.minzheng.blog.config.OssConfigProperties;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.BucketManager;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.FileInfo;
import com.qiniu.util.Auth;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.InputStream;

/**
 * oss上传策略
 *
 * @author yezhiqiu
 * @date 2021/07/28
 */
@Service("ossUploadStrategyImpl")
public class OssUploadStrategyImpl extends AbstractUploadStrategyImpl {
    @Autowired
    private OssConfigProperties ossConfigProperties;

    /**
     * 上传凭证
     */
    String token;

    Configuration cfg = new Configuration(Region.huadong());

    Auth auth;

    @Deprecated
    @Override
    public Boolean exists(String filePath) {
        try {
            FileInfo info = getBucketManger().stat(ossConfigProperties.getBucketName(), filePath);
            if (info == null) {
                return false;
            } else {
                return true;
            }
        } catch (QiniuException e) {
            e.printStackTrace();
            return false;
        }
//        return getOssClient().doesObjectExist(ossConfigProperties.getBucketName(), filePath);
    }

    @Override
    public void upload(String path, String fileName, InputStream inputStream) {
        String key = path + fileName;
        try {
            Response put = getOssClient().put(inputStream, key, token, null, null);
        } catch (QiniuException e) {
            e.printStackTrace();
        }
    }

    @Override
    public String getFileAccessUrl(String filePath) {
        return ossConfigProperties.getUrl() + filePath;
    }

    /**
     * 获取ossClient
     *
     * @return {@link UploadManager}  UploadManager
     */
    private UploadManager getOssClient() {
        UploadManager uploadManager = new UploadManager(cfg);
        auth = Auth.create(ossConfigProperties.getAccessKeyId(), ossConfigProperties.getAccessKeySecret());
        token = auth.uploadToken(ossConfigProperties.getBucketName());
        return uploadManager;
//        return new OSSClientBuilder().build(ossConfigProperties.getEndpoint(), ossConfigProperties.getAccessKeyId(), ossConfigProperties.getAccessKeySecret());
    }

    private BucketManager getBucketManger() {
        cfg = new Configuration(Region.huadong());
        auth = Auth.create(ossConfigProperties.getAccessKeyId(), ossConfigProperties.getAccessKeySecret());
        token = auth.uploadToken(ossConfigProperties.getBucketName());
        return new BucketManager(auth, cfg);
    }

}
